package com.reliable.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reliable.api.dto.user.ReliableUserLite;
import com.reliable.api.param.IdParam;
import com.reliable.api.param.record.ReliabUploadRecordPageParam;
import com.reliable.common.annotation.DataSource;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.common.core.page.TableDataInfo;
import com.reliable.common.enums.DataSourceType;
import com.reliable.framework.utils.JwtUtils;
import com.reliable.service.domain.ReliabUploadRecord;
import com.reliable.service.oss.service.OssService;
import com.reliable.service.service.ChatMessageService;
import com.reliable.service.service.IReliabUploadRecordService;
import com.reliable.service.utils.IdEncryptUtils;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;


@RestController
@RequestMapping("/reliable/upload")
@Api(value = "文件上传记录", tags = {"文件上传记录管理"})
public class ReliableUploadRecordController {

    @Autowired
    private IReliabUploadRecordService reliabUploadRecordService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private OssService ossService;


    /**
     * 文件上传查询
     */
    @ApiOperation("文件上传记录查询")
    @PostMapping("/recordList")
    public AjaxResult list (@RequestBody ReliabUploadRecordPageParam param) {
        LambdaQueryWrapper<ReliabUploadRecord> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneEmpty(param.getFileName())){
            wrapper.like(ReliabUploadRecord::getFileName, param.getFileName());
        }
        if (param.getStatus() != null){
            wrapper.eq(ReliabUploadRecord::getStatus, param.getStatus());
        }

        if (StringUtils.isNotEmpty(param.getTaskId()))
        {
            wrapper.eq(ReliabUploadRecord::getTaskId, IdEncryptUtils.decrypt(param.getTaskId()));
        }

//        ReliableUserLite currentUser = JwtUtils.getCurrentUser();
//
//        wrapper.eq(ReliabUploadRecord::getCreateBy, currentUser.getId());
        IPage<ReliabUploadRecord> page = reliabUploadRecordService.page(new Page<>(param.getPageNum(), param.getPageSize()),wrapper);
        List<ReliabUploadRecord> records = page.getRecords();
        records.forEach(record -> {
            record.setBusinessId(IdEncryptUtils.encrypt(record.getId()));
            record.setTaskBusinessId(IdEncryptUtils.encrypt(record.getTaskId()));
            record.setTaskId(null);
            record.setId(null);
        });
        TableDataInfo data = new TableDataInfo(page.getRecords(), (int) page.getTotal());
        return AjaxResult.success(data);
    }


    /**
     * 文件上传详情
     */
    @ApiOperation("文件上传记录详情")
    @PostMapping("/recordInfo")
    public AjaxResult info (@RequestBody IdParam param) {
        ReliabUploadRecord reliabUploadRecord = reliabUploadRecordService.getById(IdEncryptUtils.decrypt(param.getBusinessId()));
        reliabUploadRecord.setBusinessId(IdEncryptUtils.encrypt(reliabUploadRecord.getId()));
        reliabUploadRecord.setTaskId(null);
        reliabUploadRecord.setId(null);
        return AjaxResult.success(reliabUploadRecord);
    }


    /**
     * 导入Excel文件
     *
     * @param file Excel文件
     * @param taskId 任务ID
     * @return 操作结果
     */
    @PostMapping("/import")
    @ApiOperation("导入Excel文件")
    @DataSource(value = DataSourceType.PG)
    public DeferredResult<String> importExcel(@RequestParam("file") MultipartFile file,
                                              @RequestParam("taskId") String taskId) {
        // 设置较长的超时时间(1小时)和默认返回值
        DeferredResult<String> deferredResult = new DeferredResult<>(3600000L, "导入任务已提交，正在后台处理，请稍后查询结果");

        // 异步处理Excel导入
        CompletableFuture.supplyAsync(() -> {
                    try {
                        chatMessageService.importExcel(file, taskId);
                        return "导入任务已完成!";
                    } catch (Exception e) {
                        e.printStackTrace();
                        return "导入失败：" + e.getMessage();
                    }
                }).thenAccept(result -> deferredResult.setResult(result))
                .exceptionally(e -> {
                    deferredResult.setErrorResult(e);
                    return null;
                });

        return deferredResult;
    }



}
